<?php


namespace backend\components;

/**
 * description of VarDumper
 *
 * @author FireLoong
 */
class VarDumper extends \yii\helpers\VarDumper
{
    private static $_output;

    /**
     * Exports a configs as a string representation.
     * @param \SimpleXMLElement $configs 系统配置
     * @param int $level 深度等级
     * @param bool $arg
     * @return string
     */
    public static function xmlExport(\SimpleXMLElement $configs, $level = 0, $arg = true)
    {
        $spaces = str_repeat(' ', $level * 4);
        self::$_output = '';
        if ($arg) {
            self::$_output .= '[';
        }
        foreach ($configs->item as $item) {
            self::xmlExportInternal($item, $level);
        }
        if ($arg) {
            self::$_output .= PHP_EOL . $spaces . ']';
        }
        return self::$_output;
    }

    /**
     * @param \SimpleXMLElement $config variable to be config
     * @param int $level 深度等级
     */
    private static function xmlExportInternal(\SimpleXMLElement $config, $level)
    {
        $type = strtolower((string)$config->attributes()->type);
        $key = (string)$config->attributes()->key;
        $spaces = str_repeat(' ', $level * 4);
        self::$_output .= PHP_EOL . $spaces . '    ';
        if ($key) {
            self::$_output .= self::export($key);
            self::$_output .= ' => ';
        }
        switch ($type) {
            case 'null':
                self::$_output .= 'null';
                break;
            case 'array':
                if (empty($config)) {
                    self::$_output .= '[]';
                } else {
                    self::$_output .= '[';
                    if ($config->item) {
                        foreach ($config->item as $item) {
                            self::xmlExportInternal($item, $level + 1);
                        }
                        self::$_output .= PHP_EOL . $spaces . '    ';
                    }
                    self::$_output .= '],';
                }
                break;
            case 'function':
            case 'integer':
            case 'double':
            case 'php':
                self::$_output .= trim((string)$config) . ',';
                break;
            case 'string':
                self::$_output .= str_replace('\\\\', '\\', self::export((string)$config)) . ',';
                break;
            case 'boolean':
                self::$_output .= in_array(trim((string)$config), ['true', '1', 1], true) ? 'true' : 'false';
                self::$_output .= ',';
                break;
            default:
                self::$_output .= var_export(trim((string)$config), true) . ',';
        }
    }
}
